import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, tap } from 'rxjs';
import { map } from 'rxjs/operators';
import { InjectRepository } from '@nestjs/typeorm';
import { Log } from '@/modules/system/log/entities/log.entity';
import { Repository } from 'typeorm';
import { argumentsToString } from '@/common/utils/common';
import { Reflector } from '@nestjs/core';
import { ApiOperation } from '@nestjs/swagger';

@Injectable()
export class LogInterceptor implements NestInterceptor {
    constructor(
        @InjectRepository(Log)
        private readonly logRepository: Repository<Log>,
        private readonly reflector: Reflector,
    ) {
    }

    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        // 在这里修改请求
        const request = context.switchToHttp().getRequest();
        const handler = context.getHandler(); // 获取路由处理函数（如 login 方法）
        // response.header("X-Response-Interceptor", "true");
        // console.log("request", request);
        // 尝试获取 @ApiOperation() 的 summary
        const apiOperation = Reflect.getMetadata(
            'swagger/apiOperation', // @nestjs/swagger 的内部键（可能变化）
            handler,
        );
        const operationName = apiOperation?.summary || '接口日志';
        return next.handle().pipe(
            tap((response) => {
                console.log('response', response);
                this.logRepository.save({
                    ip: request.ip,
                    userFlag: request?.user?.username,
                    name: decodeURIComponent(request.headers['api-name']) || operationName,
                    method: request.method,
                    arguments: argumentsToString(request), // (request.body || request.params || request.query),
                    message: response.msg,
                    status: request.status,
                    path: request.originalUrl,
                    createAt: response.time,
                    type: 1,
                });
            }));
    }
}